/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Xiaobao Zeng<zengxiaobao@skyworth.com>
 * Created Time: 2017-03-30 17:17:30
 * Last Modified: 2017-06-08 15:22:57
 * File Name: admin.go
 * Description:
 */

package controllers

import (
	"encoding/json"
	"net/url"
	"strconv"

	"qkleague/account"
	"qkleague/admin"
	"qkleague/errorcode"
	"doubimeizhi.com/jsonq"
	log "github.com/cihub/seelog"
	//"qkleague/rpc/client/passport"
	rpc "qkleague/rpc/client/qingke"
)

type AdminController struct {
	//	URLSignController
	SSOLoginedController
}

//获取加盟商列表
// @router /league/list [post]
func (p *AdminController) LeagueList() {
	defer p.Output("LeagueList")

	ltype, _ := p.GetInt("type", 0)
	key := p.GetString("key", "")

	body := p.Ctx.Input.RequestBody
	qs, _ := url.ParseQuery(string(body))
	start, _ := strconv.Atoi(qs.Get("start"))
	length, _ := strconv.Atoi(qs.Get("length"))
	if length == 0 {
		length = 10
	}

	log.Debugf("LeagueList, start:%d, length:%d", start, length)

	req := &admin.ShowItemReq{}
	req.PageIndex = start / length
	req.PageSize = length
	req.Role = false

	resp := &admin.ShowItemResp{}

	err := admin.GetAdminService().ListLeague(req, resp, ltype, key)
	p.Resp["code"] = resp.Code
	p.Resp["msg"] = resp.Msg
	if err == nil {
		p.Resp["data"] = resp.Data
		p.Resp["has_more"] = resp.HasMore
		p.Resp["recordsTotal"] = resp.Total
		p.Resp["recordsFiltered"] = resp.Total
		p.Resp["draw"], _ = strconv.Atoi(qs.Get("draw"))
		return
	} else {
		p.Resp["msg"] = err.Error()
	}
}

//获取特定加盟商信息
// @router /league/some [get]
func (p *AdminController) SomeLeague() {
	defer p.Output("SomeLeague")

	ltype, _ := p.GetInt("type", 0)
	key := p.GetString("key", "")

	if err, data := admin.GetAdminService().GetSomeLeague(ltype, key); err == nil {
		p.Resp["code"] = errorcode.EC_GL_SUCCESS
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
		p.Resp["data"] = data
	} else {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = err.Error()
	}
}

//删除加盟商
// @router /league/delete [post]
func (p *AdminController) DelLeagueInfo() {
	defer p.Output("DelLeagueInfo")

	body := p.Ctx.Input.RequestBody
	log.Debugf("recv body %s", body)
	reqBody := make(map[string]interface{})
	if err := json.Unmarshal(body, &reqBody); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}

	leagueId := ""
	if val, ok := reqBody["league_id"]; ok {
		leagueId = val.(string)
	}

	if leagueId == "" {
		log.Warnf("DelLeagueInfo, league_id is not allowed empty!")
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}

	code := account.GetAccountService().DeleteUser(leagueId)
	p.Resp["code"] = code
	p.Resp["msg"] = errorcode.Msg(code)
}

//获取洗衣点列表
// @router /washroom/list [post]
func (p *AdminController) WashRoomList() {
	defer p.Output("WashRoomList")

	leagueId := p.GetString("league_id", "")
	washRoomName := p.GetString("washroom_name", "")
	washRoomId := p.GetString("washroom_id", "")
	id, _ := p.GetInt("id", 0)
	log.Debugf("leagueId:%s, washRoomName:%s, washRoomId:%s", leagueId, washRoomName, washRoomId)

	body := p.Ctx.Input.RequestBody
	qs, _ := url.ParseQuery(string(body))
	start, _ := strconv.Atoi(qs.Get("start"))
	length, _ := strconv.Atoi(qs.Get("length"))
	if length == 0 {
		length = 10
	}
	log.Debugf("WashRoomList, start:%d, length:%d", start, length)

	req := &admin.ShowItemReq{}
	req.PageIndex = start / length
	req.PageSize = length
	req.Role = false

	resp := &admin.ShowItemResp{}

	//err := admin.GetAdminService().ListWashRoom(req, resp, leagueId, washRoomName, washRoomId)
	admin.GetAdminService().ListWashRoom(req, resp, leagueId, washRoomName, washRoomId, id)
	//if err == nil {
	p.Resp["code"] = errorcode.EC_GL_SUCCESS
	p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	p.Resp["data"] = resp.Data
	p.Resp["has_more"] = resp.HasMore
	p.Resp["recordsTotal"] = resp.Total
	p.Resp["recordsFiltered"] = resp.Total
	p.Resp["draw"], _ = strconv.Atoi(qs.Get("draw"))
	/*	} else {
		p.Resp["code"] = errorcode.EC_GL_USER_HAS_NO_DATA
		p.Resp["msg"] = err.Error()
	}*/
}

//获取特定洗衣点信息
// @router /washroom/some [get]
func (p *AdminController) SomeWashRoom() {
	defer p.Output("SomeWashRoom")

	washRoomId := p.GetString("washroom_id", "")
	leagueId := p.GetString("league_id", "")
	id, _ := p.GetInt("id", 0)

	if err, data := admin.GetAdminService().GetSomeWashRoom(leagueId, washRoomId, id); err == nil {
		p.Resp["code"] = errorcode.EC_GL_SUCCESS
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
		p.Resp["data"] = data
	} else {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = err.Error()
	}
}

/*
	添加洗衣房
*/
// @router /washroom/add [post]
func (p *AdminController) AddWashroom() {
	defer p.Output("AddWashroom")

	body := p.Ctx.Input.RequestBody
	log.Infof("recv body:%s", string(body))
	req := make(map[string]interface{})
	if err := json.Unmarshal(body, &req); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}

	userId := ""
	if val, ok := req["userid"]; ok {
		userId = val.(string)
	}
	if ok, roomId, msg := rpc.AddWashRoom(userId, req); ok {
		p.Resp["code"] = errorcode.EC_GL_SUCCESS
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
		p.Resp["room_id"] = roomId

	} else {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = msg
	}
}

//删除洗衣房
//@router /washroom/delete [post]
func (p *AdminController) DelWashroom() {
	defer p.Output("DelWashroom")

	body := p.Ctx.Input.RequestBody
	req := make(map[string]interface{})
	if err := json.Unmarshal(body, &req); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}
	code, msg := rpc.DelWashRoom(req)
	p.Resp["code"] = code
	p.Resp["msg"] = msg
}

//修改洗衣房信息
//@router /washroom/modify [post]
func (p *AdminController) ModifyWashroom() {
	defer p.Output("ModifyWashroom")

	body := p.Ctx.Input.RequestBody
	log.Infof("recv body:%s", string(body))
	req := make(map[string]interface{})
	if err := json.Unmarshal(body, &req); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}
	code, msg := rpc.ModifyWashRoom(req)
	p.Resp["code"] = code
	p.Resp["msg"] = msg
}

//获取洗衣机列表
//@router /washer/list [post]
func (p *AdminController) WasherList() {
	defer p.Output("WasherList")

	leagueId := p.GetString("league_id", "")
	washRoomId := p.GetString("washroom_id", "")
	washerId := p.GetString("washer_id", "")
	log.Debugf("leagueId:%s, washRoomId:%s, washerId:%s", leagueId, washRoomId, washerId)

	body := p.Ctx.Input.RequestBody
	qs, _ := url.ParseQuery(string(body))
	start, _ := strconv.Atoi(qs.Get("start"))
	length, _ := strconv.Atoi(qs.Get("length"))
	if length == 0 {
		length = 10
	}
	log.Debugf("WashRoomList, start:%d, length:%d", start, length)

	req := &admin.ShowItemReq{}
	req.PageIndex = start / length
	req.PageSize = length
	req.Role = false

	resp := &admin.ShowItemResp{}

	err := admin.GetAdminService().ListWasher(req, resp, leagueId, washRoomId, washerId)
	p.Resp["code"] = resp.Code
	p.Resp["msg"] = resp.Msg
	if err == nil {
		p.Resp["data"] = resp.Data
		p.Resp["has_more"] = resp.HasMore
		p.Resp["recordsTotal"] = resp.Total
		p.Resp["recordsFiltered"] = resp.Total
		p.Resp["draw"], _ = strconv.Atoi(qs.Get("draw"))
		return
	} else {
		p.Resp["msg"] = err.Error()
	}
}

//获取特定洗衣机信息
// @router /washer/some [get]
func (p *AdminController) SomeWasher() {
	defer p.Output("SomeWasher")

	washerId := p.GetString("washer_id", "")

	if err, data := admin.GetAdminService().GetSomeWasher(washerId); err == nil {
		p.Resp["code"] = errorcode.EC_GL_SUCCESS
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
		p.Resp["data"] = data
	} else {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = err.Error()
	}
}

/*
	添加洗衣机
*/
// @router /washer/add [post]
func (p *AdminController) AddWahserInfo() {
	defer p.Output("AddWahserInfo")

	body := p.Ctx.Input.RequestBody
	log.Infof("receve body, %s", string(body))

	washer := make(map[string]interface{})
	if err := json.Unmarshal(body, &washer); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}

	userId := ""
	if val, ok := washer["userid"]; ok {
		userId = val.(string)
	}

	if ok, washerId, msg := rpc.AddWasher(userId, washer); ok {
		p.Resp["code"] = errorcode.EC_GL_SUCCESS
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
		p.Resp["washer_id"] = washerId
	} else {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = msg
	}
}

/*
	修改洗衣机信息
*/
// @router /washer/modify [post]
func (p *AdminController) ModifyWahserInfo() {
	defer p.Output("ModifyWahserInfo")

	body := p.Ctx.Input.RequestBody

	log.Infof("receve body, %s", string(body))
	washer := make(map[string]interface{})
	if err := json.Unmarshal(body, &washer); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}

	code, msg := rpc.ModifyWasher(washer)
	p.Resp["code"] = code
	p.Resp["msg"] = msg
}

//停启用洗衣机
// @router /washer/enable/status [post]
func (p *AdminController) EnableWasher() {
	defer p.Output("EnableWasher")

	body := p.Ctx.Input.RequestBody
	req := make(map[string]interface{})
	if err := json.Unmarshal(body, &req); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}
	_, ok := req["washer_id"]
	_, ok2 := req["enable"]
	if !ok || !ok2 {
		log.Debugf("EnableWasher, req[\"washer_id\"]:%v, req[\"enable\"]:%v", ok, ok2)
		p.Resp["code"] = errorcode.EC_WASHER_ENABLE_PARAM_ERR
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_WASHER_ENABLE_PARAM_ERR)
		return
	}

	if data := rpc.EnableWasher("web", req); data != nil {
		p.Resp["code"] = errorcode.EC_GL_SUCCESS
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
		p.Resp["run_state"] = data
	} else {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
	}
}
//获取洗衣机定价列表
//@router /washer_price/list [post]
func (p *AdminController) WasherPriceList() {
	defer p.Output("WasherPriceList")

	leagueId := p.GetString("league_id", "")
	washRoomId := p.GetString("washroom_id", "")
	washerId := p.GetString("washer_id", "")
	//log.Infof("leagueId:%s, washRoomId:%s, washerId:%s", leagueId, washRoomId, washerId)

	body := p.Ctx.Input.RequestBody
	qs, _ := url.ParseQuery(string(body))
	start, _ := strconv.Atoi(qs.Get("start"))
	length, _ := strconv.Atoi(qs.Get("length"))
	if length == 0 {
		length = 10
	}
	log.Infof("WashRoomList, start:%d, length:%d", start, length)

	req := &admin.ShowItemReq{}
	req.PageIndex = start / length
	req.PageSize = length
	req.Role = false

	resp := &admin.ShowItemResp{}

	err := admin.GetAdminService().ListWasherPrice(req, resp, leagueId, washRoomId, washerId)
	p.Resp["code"] = resp.Code
	p.Resp["msg"] = resp.Msg
	if err == nil {
		p.Resp["data"] = resp.Data
		p.Resp["has_more"] = resp.HasMore
		p.Resp["recordsTotal"] = resp.Total
		p.Resp["recordsFiltered"] = resp.Total
		p.Resp["draw"], _ = strconv.Atoi(qs.Get("draw"))

		return
	} else {
		p.Resp["msg"] = err.Error()
	}
}


//修改洗衣机定价
//@router /change_washer_price/ [post]
func (p *AdminController) ChangeWasherPrice() {
	defer p.Output("ChangeWasherPrice")
	body := p.Ctx.Input.RequestBody
	req :=make(map[string]interface{})
	if err := json.Unmarshal(body, &req); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}
	leagueId := p.GetString("league_id", "")
	washRoomId := p.GetString("washroom_id", "")
	washerId := p.GetString("washer_id", "")
	req1 := &admin.ShowItemReq{}
	resp := &admin.ShowItemResp{}
	err := admin.GetAdminService().ListWasherPrice(req1,resp, leagueId, washRoomId, washerId)
	sum :=0
	if err==nil{
		         //log.Infof("qb:%s",req)
			 qb:=req["qb"]

		if qb!=nil{
			 qb=qb.(map[string]interface{})
			 jq := jsonq.NewQuery(qb)
			 qb_a ,_ :=jq.Int("qb_a")
			 qb_b ,_ :=jq.Int("qb_b")
			 qb_c ,_ :=jq.Int("qb_c")
			 qb_d ,_ :=jq.Int("qb_d")
			 for _, dt := range resp.DWasher{
				 //log.Infof("dt:%s",dt)
				 //json.Unmarshal(qb, &req["qb"])
				 //log.Infof("qb:%s",qb)
				 //log.Infof("qb_a:%s",qb_a)
				 washer_change := &admin.QKWasherPrice{}
				 washer_change.WasherId = dt
				 washer_change.QBA = qb_a
				 washer_change.QBB = qb_b
				 washer_change.QBC = qb_c
				 washer_change.QBD = qb_d
				 log.Infof("washer_change:%s",washer_change)
				 err := admin.GetAdminService().ChangeWasherQBPrice(washer_change)
				 if err==nil{
					 sum++
				 }
			 }

		 }
		    card:=req["card"]
		 if card!=nil{
			 card:=card.(map[string]interface{})
			 jq := jsonq.NewQuery(card)
			 card_a ,_ :=jq.Int("card_a")
			 card_b ,_ :=jq.Int("card_b")
			 card_c ,_ :=jq.Int("card_c")
			 card_d ,_ :=jq.Int("card_d")
			 for _, dt := range resp.DWasher {
				 washer_change := &admin.QKWasherPrice{}
				 washer_change.WasherId = dt
				 washer_change.CardA = card_a
				 washer_change.CardB = card_b
				 washer_change.CardC = card_c
				 washer_change.CardD = card_d
				 err := admin.GetAdminService().ChangeWasherCardPrice(washer_change)
				 if err==nil{
					 sum++
				 }
			 }
	}

	}
	p.Resp["code"] = errorcode.EC_GL_SUCCESS
	p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	p.Resp["sum"] = sum

}
//向cc发送不重定向命令
//@router /washer_list/switchcc [get]
func (p *AdminController) SwitchWasher() {
	defer p.Output("SwitchWasher")

	leagueId := p.GetString("league_id", "")
	washRoomId := p.GetString("washroom_id", "")
	washerId := p.GetString("washer_id", "")
	//log.Infof("leagueId:%s, washRoomId:%s, washerId:%s", leagueId, washRoomId, washerId)
	req := &admin.ShowItemReq{}
	resp := &admin.ShowItemResp{}
	err := admin.GetAdminService().ListWasherPrice(req, resp, leagueId, washRoomId, washerId)
	sum:=0
	if err==nil{
		for _, dt := range resp.Dimei{
			imei:=dt
			num:=rpc.SwitchWasher(imei)
			sum=sum+num
		}
	}
	p.Resp["code"] = errorcode.EC_GL_SUCCESS
	p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	p.Resp["sum"] = sum
}